package com.example.dpcnb.excel.fastexcel;

import cn.idev.excel.FastExcel;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

@RequestMapping("/excel")
@RestController
@Slf4j
public class FastExcelController {

    // 注意 需要 commons 和fastexcel pom 三个pom 坐标

    @GetMapping("/download")
    public void download(HttpServletResponse response) throws IOException {
        log.info("开始下载");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("test", "UTF-8");
        response.setHeader("Content-disposition",
                "attachment;filename*=utf-8''" + fileName + ".xlsx");
        // 写入数据
        FastExcel.write(response.getOutputStream(), User.class)
                .sheet("模板")
                .doWrite(buildData());
        log.info("excel 生成完毕");
    }
    // 创建测试数据
    private List<User> buildData() {
        // 创建 User 测试数据
        User user1 = new User();
        user1.setId(1);
        user1.setName("张三");
        user1.setAge(18);
        User user2 = new User();
        user2.setId(2);
        user2.setName("李四");
        user2.setAge(19);
        return Arrays.asList(user1, user2);
    }


    @PostMapping("/upload")
    public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
        log.info("开始上传");

        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择一个文件上传！");
        }
        try {
            BaseExcelListener<User> baseExcelListener = new BaseExcelListener<>();
            FastExcel.read(file.getInputStream(), User.class,
                    baseExcelListener).sheet().doRead();
            // 得到读取数据
            List<User> dataList = baseExcelListener.getDataList();
            System.out.println(dataList);
            log.info("文件上传并处理成功");
            return ResponseEntity.ok("文件上传并处理成功！");
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件处理失败！");
        }
    }

}
